﻿#include "producttableview.h"
#include <QStandardItemModel>
#include <QDebug>

ProductTableView::ProductTableView(QWidget *parent) : MyTableView(parent)
{
    setSortingEnabled(true);

    model = new ProductStandardItemModel();
    setModel(model);
    setEditTriggers(QAbstractItemView::NoEditTriggers);

    connect(model, &ProductStandardItemModel::updateTotalValue,
            [=](int totalCount, int totalSanbao, double totalInprice)
    {
        emit this->updateTotalValue(totalCount, totalSanbao, totalInprice);
    });
}

void ProductTableView::initHiddenState(){
    initHiddenStateList("store", model->header.size());
}

void ProductTableView::insertProduct(QList<Product*> products)
{
    model->insertProduct(products);
}

void ProductTableView::setListPushButton(ListPushButton *listPushButton){
    setListPushButtonAndMenuLabel(listPushButton, model->header);
}

void ProductTableView::queryProduct(
        int limitIndex,
        QString overallQuery,
        QString typeQuery,
        QString nameQuery,
        QString primaryQuery,
        QString secondaryQuery)
{
    clear();
    DbHelper helper;

    QList<Product*> tempProducts = helper.queryProducts(
                overallQuery,
                typeQuery,
                nameQuery,
                primaryQuery,
                secondaryQuery);
    QList<Product*> products;
    if(limitIndex == 0){
        //显示全部
        model->insertProduct(tempProducts);
    }else if (limitIndex == 1) {
        //上限 库存数量>上限
        for(Product *product:tempProducts){
            if(product->count > product->upperLimit){
                products.append(product);
            }
        }
        model->insertProduct(products);
    }else{
        //下限 库存数量<下限
        for(Product *product:tempProducts){
            if(product->count < product->lowerLimit){
                products.append(product);
            }
        }
        model->insertProduct(products);
    }


    refreshHiddenState();
}

void ProductTableView::clear()
{
    model->reset();
    refreshHiddenState();
}

Product* ProductTableView::currentProduct(){
    int row = currentIndex().row();

    return model->getProduct(row);
}

void ProductTableView::loadProucts()
{
    DbHelper helper;
    QList<Product*> products = helper.getAllProducts();
    model->insertProduct(products);

    refreshHiddenState();
}

QList<Product*> ProductTableView::selectedProducts()
{
    QList<Product*> selectedProducts;

    QItemSelectionModel *select = selectionModel();
    if(!select->hasSelection()){
        return selectedProducts;
    }

    QModelIndexList rows = select->selectedRows();
    for(QModelIndex row:rows){
        selectedProducts.append(model->getProduct(row.row()));
    }

    return selectedProducts;
}
